import random
import time

from sam.util.httpUtil import get_web_driver


class WeiBoComment(object):
    def __init__(self, comment_url):
        super().__init__()
        self.browser = get_web_driver(headless=False, images_less=False)
        self.comment_url = comment_url
        self.current_batch = 0

    def __del__(self):
        if self.browser:
            self.browser.quit()
            print("无图浏览器退出")

    def login(self):
        self.browser.get("https://weibo.com/")
        time.sleep(5)
        element1 = self.browser.find_element_by_css_selector(
            '#pl_login_form > div > div.info_header > div > a:nth-child(2)')
        self.browser.execute_script("arguments[0].click();", element1)
        time.sleep(30)
        print("ok")

    def click(self, selector_str):
        _element = self.browser.find_element_by_css_selector(selector_str)
        self.browser.execute_script("arguments[0].click();", _element)

    def exists(self, selector_str):
        _element_list = self.browser.find_elements_by_css_selector(selector_str)
        return len(_element_list) > 0

    def open_search(self):
        print(f"将要访问: {self.comment_url}")
        self.browser.get(self.comment_url)
        time.sleep(5)
        # 先 切换到 按照时间
        time_dimension_selector = "#Pl_Official_WeiboDetail__71 > div > div > div > div.WB_feed_repeat.S_bg1.WB_feed_repeat_v3 > div > div.repeat_list > div.tab_feed_a.clearfix.S_line1 > div > ul > li:nth-child(2) > span > a"
        self.click(time_dimension_selector)
        time.sleep(random.randint(3, 7))
        # 加载所有的 查看更多
        print("开始加载 查看更多")
        self.comment()
        print("加载完成 所有的查看更多")
        comment_str = "#Pl_Official_WeiboDetail__71 > div > div > div > div.WB_feed_repeat.S_bg1.WB_feed_repeat_v3 > div > div.repeat_list > div:nth-child(2) > div > div > div > div.list_con > div.WB_text"
        comment_element_list = self.browser.find_elements_by_css_selector(comment_str)
        for comment_element in comment_element_list:
            print(comment_element.text)

    def comment(self):
        self.current_batch += 1
        print(f"第 {self.current_batch} 次 加载 查看更多")
        more_txt_str = "#Pl_Official_WeiboDetail__71 > div > div > div > div.WB_feed_repeat.S_bg1.WB_feed_repeat_v3 > div > div.repeat_list > div:nth-child(2) > div > div > a"
        while self.exists(more_txt_str):
            self.click(more_txt_str)
            time.sleep(random.randint(5, 8))
            self.comment()

    def search(self):
        self.login()
        self.open_search()


if __name__ == "__main__":
    bo = WeiBoComment(
        "https://weibo.com/2423763501/I6aN95bRY?refer_flag=1001030103_&type=comment#_rnd1624185123969")
    bo.search()
